#!/usr/bin/env python3
"""Claude Bridge client: run ExtendScript in Premiere Pro through the Claude Bridge panel.

The panel (Window > Extensions > Claude Bridge) must be open in Premiere,
in its own frame (not hidden behind another tab), with no modal dialog open.

  premiere doctor                              health check + exact recovery steps (run before a build)
  premiere status                              raw status.json with age
  premiere ping                                bridge + Premiere version, active project
  premiere call projectList                    call a helper from jsx/host.jsx
  premiere call sequenceList '"/path/My.prproj"'   helper args are JSON values
  premiere run script.jsx --label "What it does"
  premiere run -e 'return app.project.name;' --label "Read the project name"
  premiere run ... --max-seconds 600           watchdog for a long import (default 120 s)
  premiere restart-engine                      kill stale claudebridge CEPHtmlEngine processes

A script is an ExtendScript function body (ES3) and may `return` a plain value.
Every job shows up in the panel with its label, script and result.

Exit codes: 0 ok, 1 the script failed in Premiere, 2 usage error,
3 panel not open or host.jsx not loaded, 4 panel paused, 5 still running when
--wait ran out, 6 Premiere's script engine did not answer (restart Premiere),
7 the panel tab is hidden. `doctor` exits 0 when healthy, 1 when it found something.
"""
import argparse
import json
import os
import re
import signal
import subprocess
import sys
import time
import uuid

BASE = os.environ.get("CLAUDE_BRIDGE_DIR") or os.path.expanduser("~/.claude-bridge/premiere")  # override only for tests
INBOX = os.path.join(BASE, "inbox")
RUNNING = os.path.join(BASE, "running")
OUTBOX = os.path.join(BASE, "outbox")
STATUS = os.path.join(BASE, "status.json")
LOCK = os.path.join(BASE, "instance.lock")
STALE_S = 8.0
DEFAULT_MAX_SECONDS = 120
WATCHDOG_GRACE_S = 5           # the panel adds this to maxSeconds before it gives up on a job
HOST_LOAD_RESTART_S = 120      # hostReady false for this long = restart Premiere
PANEL_MENU = "Window > Extensions > Claude Bridge"


def read_json(path):
    try:
        with open(path) as f:
            return json.load(f)
    except (OSError, ValueError):
        return None


def read_status():
    st = read_json(STATUS)
    if not st:
        return None
    st["age_s"] = round(time.time() - st.get("ts", 0) / 1000.0, 1)
    st["open"] = bool(st.get("alive")) and st["age_s"] < STALE_S
    return st


def fail(code, msg):
    print(json.dumps({"ok": False, "error": msg}, indent=1))
    sys.exit(code)


def refuse_if_unhealthy(st):
    """One line each: why a job must not be submitted right now."""
    if not st or not st["open"]:
        fail(3, "The Claude Bridge panel is not open in Premiere (%s). Run: premiere doctor" % PANEL_MENU)
    if st.get("poisoned"):
        fail(6, "Refusing: Premiere's script engine stopped answering (a job timed out). Restart Premiere, reopen the panel, then run: premiere doctor")
    if st.get("visible") is False:
        fail(7, "Refusing: the Claude Bridge panel tab is hidden behind another tab. Bring it to the front or give it its own frame (jobs claimed while hidden never ran).")
    if st.get("paused"):
        fail(4, "The Claude Bridge panel is paused. Press Resume in the panel.")
    if not st.get("hostReady"):
        fail(3, "The panel is open but its ExtendScript (host.jsx) is not loaded. Click 'Reload host script' in the panel; if it stays unloaded for two minutes, restart Premiere.")


def submit(script, label, start_timeout, wait, max_seconds):
    refuse_if_unhealthy(read_status())
    if max_seconds is None or max_seconds <= 0:
        max_seconds = DEFAULT_MAX_SECONDS
    if wait is None:
        wait = max_seconds + WATCHDOG_GRACE_S + 30

    jid = time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]
    now_ms = int(time.time() * 1000)
    job = {"id": jid, "label": label or "", "script": script, "maxSeconds": max_seconds,
           "created": now_ms, "expires": now_ms + int(start_timeout * 1000)}
    os.makedirs(INBOX, mode=0o700, exist_ok=True)
    tmp = os.path.join(INBOX, jid + ".json.tmp")
    with open(tmp, "w") as f:
        json.dump(job, f)
    os.rename(tmp, os.path.join(INBOX, jid + ".json"))

    queued = os.path.join(INBOX, jid + ".json")
    result = os.path.join(OUTBOX, jid + ".json")
    t0 = time.time()
    while True:
        if os.path.exists(result):
            with open(result) as f:
                out = json.load(f)
            os.unlink(result)
            print(json.dumps(out, indent=1, ensure_ascii=False))
            if out.get("ok"):
                sys.exit(0)
            sys.exit(6 if out.get("timedOut") else 1)
        waited = time.time() - t0
        if os.path.exists(queued) and waited > start_timeout + 2:
            try:
                os.unlink(queued)  # withdraw it so it can never run later
                st = read_status() or {}
                why = ("closed" if not st.get("open") else
                       "busy with another job" if st.get("busy") else
                       "paused" if st.get("paused") else
                       "hidden" if st.get("visible") is False else
                       "poisoned, restart Premiere" if st.get("poisoned") else
                       "host.jsx not loaded" if not st.get("hostReady") else "idle but not polling")
                fail(3, "The panel did not pick the job up in %ds (%s). It was withdrawn. Run: premiere doctor" % (start_timeout, why))
            except FileNotFoundError:
                pass  # claimed at the last moment; keep waiting
        if waited > wait:
            fail(5, "Still running in Premiere after %ds. The result will land in %s" % (wait, result))
        time.sleep(0.15)


# ------------------------------------------------------------------ doctor

def ps_lines():
    try:
        out = subprocess.run(["ps", "-axo", "pid=,ppid=,etime=,command="], capture_output=True, text=True, check=False).stdout
    except OSError:
        return []
    rows = []
    for line in out.splitlines():
        parts = line.split(None, 3)
        if len(parts) < 4:
            continue
        try:
            rows.append({"pid": int(parts[0]), "ppid": int(parts[1]), "etime": parts[2], "cmd": parts[3]})
        except ValueError:
            continue
    return rows


def premiere_running(rows):
    return any("Adobe Premiere Pro" in r["cmd"] and "/Contents/MacOS/Adobe Premiere Pro" in r["cmd"] for r in rows)


def engines(rows=None):
    """CEPHtmlEngine processes for this panel: those whose args mention claudebridge,
    plus their child helpers (renderer/gpu) which may not repeat the extension id."""
    rows = rows if rows is not None else ps_lines()
    found = {}
    for r in rows:
        if "CEPHtmlEngine" in r["cmd"] and "claudebridge" in r["cmd"].lower():
            m = re.search(r"--type=(\S+)", r["cmd"])
            found[r["pid"]] = dict(r, kind=m.group(1) if m else "engine")
    changed = True
    while changed:
        changed = False
        for r in rows:
            if r["pid"] not in found and r["ppid"] in found and "CEPHtmlEngine" in r["cmd"]:
                m = re.search(r"--type=(\S+)", r["cmd"])
                found[r["pid"]] = dict(r, kind=m.group(1) if m else "helper")
                changed = True
    return sorted(found.values(), key=lambda e: (e["kind"] != "engine", e["pid"]))


def owner_engine(st, eng):
    """The engine pid whose process tree contains status.json's pid (the panel page
    runs in a renderer helper, so st["pid"] is a child of the engine, not the engine)."""
    if not st or not st.get("pid"):
        return None
    by_pid = {e["pid"]: e for e in eng}
    pid = st["pid"]
    for _ in range(6):
        e = by_pid.get(pid)
        if not e:
            return None
        if e["kind"] == "engine":
            return e["pid"]
        pid = e["ppid"]
    return None


def list_jobs(folder):
    out = []
    try:
        names = sorted(n for n in os.listdir(folder) if n.endswith(".json"))
    except OSError:
        return out
    for n in names:
        path = os.path.join(folder, n)
        job = read_json(path) or {}
        try:
            age = round(time.time() - os.stat(path).st_mtime)
        except OSError:
            age = None
        out.append({"id": job.get("id") or n[:-5], "label": job.get("label", ""), "age_s": age,
                    "maxSeconds": job.get("maxSeconds")})
    return out


def fmt_age(ms):
    if not ms:
        return "?"
    s = max(0, time.time() - ms / 1000.0)
    return "%ds" % s if s < 90 else "%dm%02ds" % (s // 60, s % 60)


def doctor():
    rows = ps_lines()
    st = read_status()
    lock = read_json(LOCK)
    eng = engines(rows)
    mains = [e for e in eng if e["kind"] == "engine"]
    running = list_jobs(RUNNING)
    inbox = list_jobs(INBOX)
    ppro = premiere_running(rows)
    problems = []   # each: one recovery step, in the order to do them

    print("Claude Bridge doctor  %s" % time.strftime("%Y-%m-%d %H:%M:%S"))
    print("queue:        %s" % BASE)
    print("Premiere:     %s" % ("running" if ppro else "NOT running"))
    if st:
        print("status.json:  written %ss ago  alive=%s  version=%s  pid=%s  instance=%s" % (
            st["age_s"], st.get("alive"), st.get("version"), st.get("pid"), st.get("instance")))
        print("              hostReady=%s  hostLoading=%s  visible=%s  poisoned=%s  paused=%s  busy=%s" % (
            st.get("hostReady"), st.get("hostLoading"), st.get("visible"), st.get("poisoned"), st.get("paused"), st.get("busy")))
        print("              jobsRun=%s  timeouts=%s  lateAnswers=%s  host=%s" % (
            st.get("jobsRun"), st.get("timeouts"), st.get("lateAnswers"),
            (st.get("host") or {}).get("version") if isinstance(st.get("host"), dict) else st.get("host")))
        if st.get("busy"):
            print("              running '%s' for %s, watchdog fires in %s" % (
                st.get("current"), fmt_age(st.get("currentStarted")),
                "%ds" % max(0, (st.get("deadline") or 0) / 1000.0 - time.time()) if st.get("deadline") else "?"))
    else:
        print("status.json:  missing or unreadable (the panel has never run, or the folder is wrong)")
    if lock:
        print("instance.lock: instance=%s  pid=%s  started %s ago" % (lock.get("instance"), lock.get("pid"), fmt_age(lock.get("started"))))
    else:
        print("instance.lock: none")
    print("engines:      %d claudebridge CEPHtmlEngine process(es)%s" % (
        len(mains), ", %d helper(s)" % (len(eng) - len(mains)) if len(eng) > len(mains) else ""))
    owner = owner_engine(st, eng) if (st and st["open"]) else None
    for e in eng:
        tag = ""
        if st and st.get("pid") == e["pid"]:
            tag = "   <- status.json pid (panel page)"
        elif owner and e["pid"] == owner:
            tag = "   <- owns the panel page"
        print("              pid %-6d ppid %-6d up %-10s %s%s" % (e["pid"], e["ppid"], e["etime"], e["kind"], tag))
    print("running/:     %d job(s)" % len(running))
    for j in running:
        print("              %s  '%s'  %ss old  maxSeconds=%s" % (j["id"], j["label"], j["age_s"], j["maxSeconds"]))
    print("inbox/:       %d job(s) waiting" % len(inbox))

    # ---- verdict
    fresh = bool(st and st["open"])
    if not ppro:
        problems.append("Premiere is not running. Start it, open the project, then open the panel: %s." % PANEL_MENU)
    if len(mains) > 1:
        keep = owner if fresh else None
        stale = [e["pid"] for e in mains if e["pid"] != keep]
        problems.append("%d panel engines are running; only one should. %s  Then close and reopen the panel (%s)." % (
            len(mains),
            "Kill the stale one(s): kill %s   (or: premiere restart-engine; it keeps pid %s, the one writing status.json)."
            % (" ".join(str(p) for p in stale), keep) if keep else
            "None of them is writing a fresh status.json, so kill them all: kill %s   (or: premiere restart-engine)." % " ".join(str(p) for p in stale),
            PANEL_MENU))
    elif ppro and not mains and not fresh:
        problems.append("The panel is not open (no claudebridge engine, status.json %s). Open it: %s." % (
            "is %ss old" % st["age_s"] if st else "missing", PANEL_MENU))
    elif mains and not fresh:
        e = mains[0]
        problems.append("Engine pid %d has been up %s but status.json is %s: the panel page is dead or frozen. Close and reopen the panel (%s); if status.json stays stale, kill %d (premiere restart-engine) and reopen." % (
            e["pid"], e["etime"], "%ss old" % st["age_s"] if st else "missing", PANEL_MENU, e["pid"]))
    if fresh and lock and lock.get("instance") != st.get("instance"):
        problems.append("instance.lock names instance %s (pid %s) but status.json comes from %s (pid %s): two panels disagree. Close every Claude Bridge panel tab, run premiere restart-engine, then open the panel once." % (
            lock.get("instance"), lock.get("pid"), st.get("instance"), st.get("pid")))
    if fresh and st.get("poisoned"):
        problems.append("A job timed out: Premiere's script engine did not answer. Restart Premiere (Cmd+Q; if it will not quit, Force Quit it from the Apple menu), reopen the project, then open the panel. Reason recorded: %s" % st.get("poisonedReason"))
    if fresh and not st.get("hostReady"):
        since = fmt_age(st.get("hostLoadStarted"))
        waited = (time.time() - st["hostLoadStarted"] / 1000.0) if st.get("hostLoadStarted") else 0
        if st.get("hostLoading") and waited >= HOST_LOAD_RESTART_S:
            problems.append("host.jsx has not loaded for %s (hostReady false, the load never answered). Premiere's script engine is stuck: restart Premiere, reopen the project, then open the panel." % since)
        elif st.get("hostLoading"):
            problems.append("host.jsx is still loading (%s). Wait; if hostReady stays false after two minutes, restart Premiere." % since)
        else:
            problems.append("host.jsx failed to load (hostReady false). Click 'Reload host script' in the panel; if hostReady stays false after two minutes, restart Premiere.")
    if fresh and st.get("visible") is False:
        problems.append("The panel tab is hidden behind another tab. Bring it to the front or drag it into its own frame; jobs claimed while hidden never ran, so the panel and the client both hold jobs until it is visible.")
    if fresh and st.get("paused"):
        problems.append("The panel is paused. Press Resume in the panel.")
    if fresh and not st.get("busy") and running:
        problems.append("%d job file(s) sit in running/ while the panel is idle. They are reported as interrupted the next time the panel starts; close and reopen the panel to clear them." % len(running))
    if not fresh and running:
        problems.append("%d job(s) in running/ from a panel that is gone; they will be reported as interrupted when the panel next opens, nothing to do." % len(running))

    print()
    if problems:
        print("Verdict: %d thing(s) to fix, in this order:" % len(problems))
        for i, p in enumerate(problems, 1):
            print("  %d. %s" % (i, p))
        return 1
    if fresh and st.get("busy"):
        print("Verdict: healthy, busy with '%s' (started %s ago)." % (st.get("current"), fmt_age(st.get("currentStarted"))))
    else:
        print("Verdict: healthy, ready for jobs.")
    return 0


def restart_engine(kill_all, dry_run):
    rows = ps_lines()
    st = read_status()
    eng = engines(rows)
    mains = [e for e in eng if e["kind"] == "engine"]
    if not eng:
        print("No claudebridge CEPHtmlEngine process is running; nothing to kill. Open the panel: %s" % PANEL_MENU)
        return 0
    keep = None
    if not kill_all and st and st["open"] and len(mains) > 1:
        keep = owner_engine(st, eng)
    targets = [e for e in eng if e["pid"] != keep and e["ppid"] != keep]
    if not kill_all and len(mains) == 1 and st and st["open"] and owner_engine(st, eng) == mains[0]["pid"]:
        print("Only engine pid %d is running and it is writing a fresh status.json; nothing is stale. Use --all to kill it anyway." % mains[0]["pid"])
        return 0
    if not targets:
        print("Nothing stale to kill.")
        return 0
    if keep:
        print("Keeping pid %d (it wrote status.json %ss ago)." % (keep, st["age_s"]))
    for e in targets:
        print("%s pid %d (%s, up %s)" % ("Would kill" if dry_run else "Killing", e["pid"], e["kind"], e["etime"]))
        if dry_run:
            continue
        try:
            os.kill(e["pid"], signal.SIGTERM)
        except ProcessLookupError:
            pass
        except PermissionError:
            print("  no permission to kill %d; run: kill -9 %d" % (e["pid"], e["pid"]))
    if dry_run:
        return 0
    deadline = time.time() + 3
    while time.time() < deadline:
        alive = [e for e in targets if any(r["pid"] == e["pid"] for r in ps_lines())]
        if not alive:
            break
        time.sleep(0.3)
    for e in alive:
        print("pid %d ignored SIGTERM; sending SIGKILL" % e["pid"])
        try:
            os.kill(e["pid"], signal.SIGKILL)
        except (ProcessLookupError, PermissionError):
            pass
    print("Done. Now close every Claude Bridge panel tab in Premiere and open the panel once (%s), then run: premiere doctor" % PANEL_MENU)
    if st and st.get("poisoned"):
        print("status.json still says poisoned: the engine was not the problem, Premiere's script engine is. Restart Premiere.")
    return 0


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd")
    sub.add_parser("status")
    sub.add_parser("doctor", help="health check with exact recovery steps")
    rp = sub.add_parser("restart-engine", help="kill stale claudebridge CEPHtmlEngine processes")
    rp.add_argument("--all", action="store_true", help="kill every claudebridge engine, including the one writing status.json")
    rp.add_argument("--dry-run", action="store_true", help="only show what would be killed")
    for name in ("ping", "run", "call"):
        p = sub.add_parser(name)
        if name == "run":
            p.add_argument("file", nargs="?", help="script file, or - for stdin")
            p.add_argument("-e", dest="code", help="script text")
        if name == "call":
            p.add_argument("helper")
            p.add_argument("args", nargs="*", help="JSON values")
        p.add_argument("--label", default="")
        p.add_argument("--timeout", type=float, default=20, help="seconds to wait for the panel to start the job")
        p.add_argument("--max-seconds", type=float, default=DEFAULT_MAX_SECONDS, dest="max_seconds",
                       help="watchdog: seconds Premiere may take to answer before the job is reported as timed out (default %d)" % DEFAULT_MAX_SECONDS)
        p.add_argument("--wait", type=float, default=None, help="seconds to wait for the result (default: max-seconds + 35)")
    a = ap.parse_args()

    if a.cmd == "status":
        st = read_status()
        print(json.dumps(st or {"open": False, "error": "no status file: the panel has never run"}, indent=1))
        sys.exit(0 if st and st["open"] else 3)
    if a.cmd == "doctor":
        sys.exit(doctor())
    if a.cmd == "restart-engine":
        sys.exit(restart_engine(a.all, a.dry_run))
    if a.cmd == "ping":
        submit("return __ClaudeBridge.ping();", a.label or "Check the connection", a.timeout, a.wait, a.max_seconds)
    if a.cmd == "call":
        if not re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", a.helper):
            fail(2, "Bad helper name: " + a.helper)
        parts = []
        for x in a.args:
            try:
                parts.append(json.dumps(json.loads(x)))
            except ValueError:
                fail(2, "Helper arguments must be JSON values, e.g. '\"text\"' or '[1,2]': " + x)
        script = "return __ClaudeBridge.%s(%s);" % (a.helper, ", ".join(parts))
        submit(script, a.label or ("%s(%s)" % (a.helper, ", ".join(parts)))[:200], a.timeout, a.wait, a.max_seconds)
    if a.cmd == "run":
        if a.code is not None:
            script = a.code
        elif a.file == "-":
            script = sys.stdin.read()
        elif a.file:
            with open(a.file) as f:
                script = f.read()
        else:
            fail(2, "Give a script file, - for stdin, or -e 'code'.")
        submit(script, a.label, a.timeout, a.wait, a.max_seconds)
    ap.print_help()
    sys.exit(2)


if __name__ == "__main__":
    main()
